package ysq.xyg.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.controller.BaseController;
import ysq.xyg.base.extend.shiro.AllUserPasswordToken;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.sys.dao.SysUserDao;
import ysq.xyg.sys.model.po.*;
import ysq.xyg.sys.model.vo.SysDepartVo;
import ysq.xyg.sys.model.vo.SysRoleVo;
import ysq.xyg.sys.model.vo.SysUserVo;
import ysq.xyg.sys.service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统管理-用户信息service实现
 *
 * @author shengQiang yu
 * @date 2019-3-30 11:24:36
 */
@Service("sysUserService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser> implements SysUserService {

    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysLogLoginService sysLogLoginService;

    private SysUser sysUser;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysDepartService sysDepartService;
    @Autowired
    public void setBaseDao(SysUserDao sysUserDao) {
        this.baseDao = sysUserDao;
    }


    /**
     * 登录
     *
     * @param loginName 登录名
     * @param password 登录密码
     * @param autoLogin 自动登录：1、是，2、否
     * @return
     * @author shengQiang yu
     * @date 2019-04-08 11:27
     */
    public ReturnEntity WebLogin(HttpServletRequest request, HttpServletResponse response, String loginName, String password, String autoLogin) {
        //用户名和密码为空验证
        if (StringUtil.isEmpty(loginName) || StringUtil.isEmpty(password)) {
            return new ReturnEntity(BaseConstant.FAIL,"登录名或密码为空");
        }
        SysLogLogin sysLogLogin=new SysLogLogin(loginName,ServletUtil.getClientIP(request));

        //提交主体验证到shiro
        AllUserPasswordToken token = new AllUserPasswordToken(loginName, password);
        Subject subject=SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (DisabledAccountException e) {
            sysLogLogin.setOperStatus(BaseConstant.SYS_OPERATOR_STATUS_FAIL);
            sysLogLogin.setErrorMsg("账号被禁用!");
            sysLogLoginService.insert(sysLogLogin);
            return new ReturnEntity(BaseConstant.FAIL,"账号被禁用!");
        } catch (UnknownAccountException e) {
            sysLogLogin.setOperStatus(BaseConstant.SYS_OPERATOR_STATUS_FAIL);
            sysLogLogin.setErrorMsg("登录名错误!");
            sysLogLoginService.insert(sysLogLogin);
            return new ReturnEntity(BaseConstant.FAIL,"登录名错误!");
        } catch (AuthenticationException e) {
            sysLogLogin.setOperStatus(BaseConstant.SYS_OPERATOR_STATUS_FAIL);
            sysLogLogin.setErrorMsg("密码错误!");
            sysLogLoginService.insert(sysLogLogin);
            return new ReturnEntity(BaseConstant.FAIL,"密码错误!");
        }
        sysLogLogin.setOperStatus(BaseConstant.SYS_OPERATOR_STATUS_SUCCESS);
        sysLogLoginService.insert(sysLogLogin);

        SysUser sysUser = (SysUser) subject.getPrincipal();
        sysUser.setLastLoginTime(new Date());
        sysUser.setIpAddress(sysLogLogin.getOperIp());
        updateByPrimaryKey(sysUser);
        //baseLogLoginService.insert(baseLogLogin);
        request.getSession().setAttribute(BaseConstant.SESSION_CURRENT_USER, sysUser);
        if(BaseConstant.CODE_AUTOLOGIN_Y.equals(autoLogin)){
            BaseController.CookiesAddObject(request,response,BaseConstant.COOKIE_LOGINNAME,loginName);
            BaseController.CookiesAddObject(request,response,BaseConstant.COOKIE_PASSWORD,password);
        }else{
            BaseController.CookiesDeleteObject(request,response,BaseConstant.COOKIE_LOGINNAME);
            BaseController.CookiesDeleteObject(request,response,BaseConstant.COOKIE_PASSWORD);
        }
        return new ReturnEntity();
    }
    /**
     * 退出
     *
     * @author shengQiang yu
     * @date 2019-04-08 11:27
     */
    public ReturnEntity webExit(HttpServletRequest request) {
        BaseController.SessionDeleteObject(request, BaseConstant.SESSION_CURRENT_USER);
        SecurityUtils.getSubject().logout();
        return new ReturnEntity();
    }

    /**
     * 分页查询
     *
     * @param sysUserVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity pageLeft(SysUserVo sysUserVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<SysUser> list = sysUserDao.listLeft(sysUserVo);
        PageInfo<SysUser> page=new PageInfo<SysUser>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 分页查询
     *
     * @param sysUserVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity page(SysUserVo sysUserVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<SysUser> list = acceptList(sysUserVo);
        PageInfo<SysUser> page=new PageInfo<SysUser>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改个人信息
     *
     * @param sysUserVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity updateNews(HttpServletRequest request,SysUserVo sysUserVo, SysUser currentUser) {
        SysUser sysUser=selectByPrimaryKey(currentUser.getId());

        if(StrUtil.isNotEmpty(sysUserVo.getLoginName())){
           sysUser.setLoginName(sysUserVo.getLoginName());
        }
        if(StrUtil.isNotEmpty(sysUserVo.getUserName())){
            sysUser.setUserName(sysUserVo.getUserName());
        }
        if(StrUtil.isNotEmpty(sysUserVo.getUserLogo())){
            sysUser.setUserLogo(sysUserVo.getUserLogo());
        }
        if(StrUtil.isNotEmpty(sysUserVo.getUserSex())){
            sysUser.setUserSex(sysUserVo.getUserSex());
        }
        if(StrUtil.isNotEmpty(sysUserVo.getUserPhone())){
            sysUser.setUserPhone(sysUserVo.getUserPhone());
        }
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateUser(currentUser.getId());
        int num=updateByPrimaryKey(sysUser);
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        request.getSession().setAttribute(BaseConstant.SESSION_CURRENT_USER,sysUser);
        return new ReturnEntity();
    }

    /**
     * 添加下级用户
     *
     * @param sysUserVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity addShare(SysUserVo sysUserVo, SysUser currentUser) {
        //获取部门
        List<SysDepart> sysDepartList=sysDepartService.acceptList(new SysDepartVo());
        List<SysRole> sysRoleList=sysRoleService.acceptList(new SysRoleVo());
        if(StrUtil.isNotEmpty(sysUserVo.getDepartName())){
            for(SysDepart sysDepart:sysDepartList){
                if(sysUserVo.getDepartName().equals(sysDepart.getName())){
                    sysUserVo.setDepartId(sysDepart.getId());
                    break;
                }
            }
        }
        if(StrUtil.isNotEmpty(sysUserVo.getRoleName())){
            for(SysRole sysRole:sysRoleList){
                if(sysUserVo.getRoleName().equals(sysRole.getRoleName())){
                    sysUserVo.setRoleId(sysRole.getId());
                    break;
                }
            }
        }
        return addOrUpdate(sysUserVo,currentUser);
    }
    /**
     * 修改
     *
     * @param sysUserVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity addOrUpdate(SysUserVo sysUserVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(sysUserVo.getId())){
            sysUser=new SysUser(currentUser);
            sysUser.setSalt(RandomUtil.randomString(8));
            Md5Hash pswMd5 = new Md5Hash(sysUserVo.getPassword(), sysUser.getSalt());
            sysUser.setPassword(pswMd5.toString());
            sysUser.setMoney(0);
            isUpate=false;
            sysUser.setOneIntroduce(currentUser.getId());
            sysUser.setTwoIntroduce(currentUser.getOneIntroduce());
        }else{
            sysUser=selectByPrimaryKey(sysUserVo.getId());
            if(ObjectUtil.isNull(sysUser)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }

            if(!(sysUserVo.getPassword().equals(sysUser.getPassword()))){
                //修改了密码
                Md5Hash pswMd5 = new Md5Hash(sysUserVo.getPassword(), sysUser.getSalt());
                sysUser.setPassword(pswMd5.toString());
            }
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateUser(currentUser.getId());
        }
        sysUser.setRoleId(sysUserVo.getRoleId());
        sysUser.setUserType(sysUserVo.getUserType());
        sysUser.setLoginName(sysUserVo.getLoginName());
        sysUser.setUserName(sysUserVo.getUserName());
        if(StrUtil.isEmpty(sysUserVo.getUserLogo())){
            sysUser.setUserLogo("/image/avatar_default.jpg");
        }else{
            sysUser.setUserLogo(sysUserVo.getUserLogo());
        }

        sysUser.setUserSex(sysUserVo.getUserSex());
        sysUser.setUserPhone(sysUserVo.getUserPhone());
        sysUser.setLastLoginTime(sysUserVo.getLastLoginTime());
        sysUser.setIpAddress(sysUserVo.getIpAddress());
        sysUser.setDepartId(sysUserVo.getDepartId());
        sysUser.setStatus(sysUserVo.getStatus());
        sysUser.setSort(sysUserVo.getSort());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(sysUser);
        }else{
            num=insert(sysUser);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    /**
     * 重置密码
     *
     * @param id 对象id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity resetPassword(String id, SysUser currentUser) {
        SysUser sysUser=selectByPrimaryKey(id);
        if(sysUser==null){
            return new ReturnEntity(BaseConstant.FAIL,"用户id不存在！");
        }
        sysUser.setSalt(RandomUtil.randomString(8));
        String password=RandomUtil.randomString(6);
        Md5Hash pswMd5 = new Md5Hash(password, sysUser.getSalt());
        sysUser.setPassword(pswMd5.toString());
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateUser(currentUser.getId());
        int num=updateByPrimaryKey(sysUser);
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity(password);
    }
    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public ReturnEntity delete(String id, SysUser currentUser) {
        SysUser sysUser=selectByPrimaryKey(id);
        if(sysUser!=null){
            sysUser.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(sysUser);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param sysUserVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author shengQiang yu
     * @date 2019-3-30 11:24:36
     */
    public List<SysUser> acceptList(SysUserVo sysUserVo){
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(sysUserVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",sysUserVo.getRemoveTag());
        }
        if(StringUtil.isNotEmpty(sysUserVo.getLoginName())){
            criteria.andEqualTo("loginName",sysUserVo.getLoginName());
        }
        if(StringUtil.isNotEmpty(sysUserVo.getStatus())){
            criteria.andEqualTo("status",sysUserVo.getStatus());
        }
        if(StringUtil.isNotEmpty(sysUserVo.getUserName())){
            criteria.andLike("userName","%"+sysUserVo.getUserName()+"%");
        }
        if(StringUtil.isNotEmpty(sysUserVo.getUserSex())){
            criteria.andEqualTo("userSex",sysUserVo.getUserSex());
        }
        if(StringUtil.isNotEmpty(sysUserVo.getUserType())){
            criteria.andEqualTo("userType",sysUserVo.getUserType());
        }
        if(StringUtil.isNotEmpty(sysUserVo.getUserPhone())){
            criteria.andLike("userPhone","%"+sysUserVo.getUserPhone()+"%");
        }
        example.setOrderByClause(" update_time desc");
        return sysUserDao.selectByExample(example);
    }
    /**
     * 获取组织机构和人员树
     *
     * @param sysUserVo 对象
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    @Override
    public ReturnEntity dTreeList(SysUserVo sysUserVo) {
        List<SysUser> sysUserList = acceptList(sysUserVo);
        List<SysDepart> sysDepartList = sysDepartService.acceptList(new SysDepartVo());
        List<Map<String, Object>> dtreeEntityList = new ArrayList<Map<String, Object>>();
        for (SysDepart sysDepart : sysDepartList) {
            Map<String, Object> dtreeEntity = new HashedMap();
            dtreeEntity.put("id", sysDepart.getId());
            dtreeEntity.put("title", sysDepart.getName());
            dtreeEntity.put("parentId", StrUtil.isEmpty(sysDepart.getParentId()) ? "0" : sysDepart.getParentId());
            dtreeEntity.put("isLast", false);
            Map<String, String> m = new HashedMap();
            m.put("type", "0");
            m.put("isChecked", "0");
            List<Map<String, String>> dtreeCheckEntityList = new ArrayList<Map<String, String>>();
            dtreeCheckEntityList.add(m);
            dtreeEntity.put("checkArr", dtreeCheckEntityList);
            dtreeEntityList.add(dtreeEntity);
        }
        for (SysUser sysUser : sysUserList) {
            Map<String, Object> dtreeEntity = new HashedMap();
            dtreeEntity.put("id", sysUser.getId());
            dtreeEntity.put("title", sysUser.getUserName());
            dtreeEntity.put("parentId", sysUser.getDepartId());
            dtreeEntity.put("isLast", true);
            Map<String, String> m = new HashedMap();
            m.put("type", "0");
            m.put("isChecked", "0");
            List<Map<String, String>> dtreeCheckEntityList = new ArrayList<Map<String, String>>();
            dtreeCheckEntityList.add(m);
            dtreeEntity.put("checkArr", dtreeCheckEntityList);
            dtreeEntityList.add(dtreeEntity);
        }
        return new ReturnEntity(dtreeEntityList);
    }
}
